import requests
import json


def agent():
	#  #################  Agent  每台服务器都有 #################
	# # 采集本机的信息  执行命令
	import subprocess

	v1 = subprocess.getoutput('ipconfig')
	v1 = v1[20:30]
	print(v1)

	v2 = subprocess.getoutput('dir')
	v2 = v2[2:12]
	print(v2)

	# 发送数据

	url = 'http://127.0.0.1:8000/asset/'
	info = {'k1': {'ens333': '中文'}, 'k2': {'ens333': 'xxxx'}}
	response = requests.post(
		url=url,
		# data={'k1': {'ens333': 'xxxx'}, 'k2': {'ens333': 'xxxx'}},
		# json={'k1': {'ens333': '中文'}, 'k2': {'ens333': 'xxxx'}},
		data=json.dumps(info).encode('utf-8')
	)
	print(response.text)


def ssh():
	#  #################  SSH  放在中控机 放一份 #################

	url = 'http://127.0.0.1:8000/asset/'
	response = requests.get(url=url, )
	# ret = response.text  # 文本字符串
	ret = response.json()  # 文本字符串
	print(ret, type(ret))


import paramiko

# 创建SSH对象
ssh = paramiko.SSHClient()

# 允许连接不在know_hosts文件中的主机
ssh.set_missing_host_key_policy(paramiko.AutoAddPolicy())
# 连接服务器
ssh.connect(hostname='192.168.16.140', port=22, username='root', password='centos')
# 执行命令
stdin, stdout, stderr = ssh.exec_command('ifconfig')
# 获取命令结果
result = stdout.read()
print(result)
# 关闭连接
ssh.close()


def salt():
	#  #################  salt 放在中控机 放一份 #################

	import salt.client
	local = salt.client.LocalClient()
	result = local.cmd('s19minion', 'cmd.run', ['ifconfig'])


mode = 'agent'

if mode == 'agent':
	agent()
elif mode == 'ssh':
	ssh()
elif mode == 'salt':
	salt()
